package cc.linker.steplink.crm.merchanth5.service.impl;


import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.form.FormRequest;
import cc.linker.steplink.crm.commons.model.FormLoginDto;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.FormFilter;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchanth5.dao.EnrollActiveDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.MerchantSalerDao;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MerchantSalerServiceImpl implements MerchantSalerService {

    @Autowired
    private MerchantSalerDao merchantSalerDao;
    @Autowired
    private EnrollActiveDao enrollActiveDao;
    @Autowired
    private MallBoomService mallBoomService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FormFilter formFilter;
    @Autowired
    private FormRequest formRequest;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private RequestFilter requestFilter;
    @Autowired
    private MallDao mallDao;

    @Override
    public Boolean addExtensionAgent(Map<String, String> params) {
        return merchantSalerDao.addExtensionAgent(params);
    }

    @Override
    public List<Map<String, String>> getExtensionAgentList(String customerId, String orgId) {
        return merchantSalerDao.getExtensionAgentList(customerId, orgId);
    }

    @Override
    public Integer getSonCustomerCount(String customerId, String orgId, Integer payMode) {
        return merchantSalerDao.getSonCustomerCount(customerId, orgId, payMode);
    }

    @Override
    public Integer getSonCustomerCountBack(String customerId, String orgId, Integer type) {
        return merchantSalerDao.getSonCustomerCountBack(customerId, orgId, type);
    }

    @Override
    public List<Map<String, String>> getCustomerSonListAgent(String customerId, String orgId, Integer payMode) {
        return merchantSalerDao.getCustomerSonListAgent(customerId, orgId, payMode);
    }

    @Override
    public List<Map<String, Object>> getCustomerSonList(Map<String, Object> param) {
        return merchantSalerDao.getCustomerSonList(param);
    }

    @Override
    public Map<String, String> getCustomerBaseInfo(String customerId) {
        return merchantSalerDao.getCustomerBaseInfo(customerId);
    }

    @Override
    public String getPromoterName(String customerId, String orgId) {
        return merchantSalerDao.getPromoterName(customerId, orgId);
    }

    @Override
    public Map<String, String> getSalerInfo(String customerId, String orgId) {
        return merchantSalerDao.getSalerInfo(customerId, orgId);
    }

    @Override
    public Map<String, String> getStoreInfo(String customerId, String orgId, Integer customerType) {
        return merchantSalerDao.getStoreInfo(customerId, orgId, customerType);
    }

    @Override
    public Map<String, String> getOrgInfo(String orgId) {
        return merchantSalerDao.getOrgInfo(orgId);
    }

    @Override
    public Integer getAgentCount(String customerId, String orgId) {
        return merchantSalerDao.getAgentCount(customerId, orgId);
    }

    @Override
    public Integer getcAgentCount(String customerId, String orgId) {
        return merchantSalerDao.getcAgentCount(customerId, orgId);
    }

    @Override
    public Integer getMerchantOrderCount(String customerId) {
        return merchantSalerDao.getMerchantOrderCount(customerId);
    }

    @Override
    public Integer getMerchantOrderCountToday(String customerId) {
        return merchantSalerDao.getMerchantOrderCountToday(customerId);
    }

    @Override
    public Integer getMerchantOrderCountToSend(String customerId) {
        return merchantSalerDao.getMerchantOrderCountToSend(customerId);
    }

    @Override
    public Integer getSumGoodsMoney(String customerId, String orgId) {
        return merchantSalerDao.getSumGoodsMoney(customerId, orgId);
    }

    @Override
    public Integer getSumGoodsMoneyToday(String customerId, String orgId) {
        return merchantSalerDao.getSumGoodsMoneyToday(customerId, orgId);
    }

    @Override
    public Integer getProfitWithdrawable(String customerId, String orgId) {
        return merchantSalerDao.getProfitWithdrawable(customerId, orgId);
    }

    @Override
    public Long getProfitToSettlement(String customerId, String orgId) {
        return merchantSalerDao.getProfitToSettlement(customerId, orgId);
    }

    @Override
    public Boolean checkSaler(String orgId) {
        return merchantSalerDao.checkSaler(orgId) == 0;
    }

    @Override
    public void addSalerNum(String orgId) {
        merchantSalerDao.addSalerNum(orgId);
    }

    @Override
    public Boolean checkPromoter(String orgId) {
        return merchantSalerDao.checkPromoter(orgId) == 0;
    }

    @Override
    public void addPromoterNum(String orgId) {
        merchantSalerDao.addPromoterNum(orgId);
    }

    @Override
    public void reducePromoterNum(String orgId) {
        merchantSalerDao.reducePromoterNum(orgId);
    }

    @Override
    public Boolean checkAgent(String orgId) {
        return merchantSalerDao.checkAgent(orgId) == 0;
    }

    @Override
    public void addAgentNum(String orgId) {
        merchantSalerDao.addAgentNum(orgId);
    }

    @Override
    public void reduceAgentNum(String orgId) {
        merchantSalerDao.reduceAgentNum(orgId);
    }

    @Override
    public List<Map<String, Object>> getPageList(String orgId, String customerId) {
        List<Map<String, Object>> pageList;
        String pageListStr = stringRedisTemplate.opsForValue().get("home:pagelist_" + orgId + "_" + customerId);
        if (StringUtils.isEmpty(pageListStr)) {
            pageList = merchantSalerDao.getPageList(orgId, customerId);
            for (Map<String, Object> da : pageList) {
                String goodsGroupName = "";
                if (!StringUtils.isEmpty(da.get("goodsGroupId"))) {
                    int showType = Integer.parseInt(da.get("showType").toString());
                    int goodsGroupId = Integer.parseInt(da.get("goodsGroupId").toString());
                    if (goodsGroupId < 1) {
                        if (goodsGroupId == 0) {
                            goodsGroupName = "默认分组";
                        }
                        if (goodsGroupId == -1) {
                            goodsGroupName = "全部分组";
                        }
                    } else {
                        goodsGroupName = merchantSalerDao.getGoodsGroupNameById(da.get("goodsGroupId").toString());
                    }
                    if (StringUtils.isEmpty(goodsGroupName) || 2 == showType) {
                        goodsGroupName = "商品分组";
                    }
                }
                da.put("goodsGroupName", goodsGroupName);
                da.put("goodsCount", 0);
                da.put("enrollCount", 0);
                Integer moduleType = (Integer) da.get("moduleType");
                switch (moduleType) {
                    case 1:
                    case 2:
                        List<Map<String, Object>> imageList = merchantSalerDao.getPageImageList((String) da.get("id"));
                        da.put("items", imageList);
                        break;
                    case 3:
                    case 4:
                    case 10:
                        this.getGoodsItems(orgId, customerId, da, moduleType, 0, 0);
                        break;
                    case 5:
                        List<Map<String, Object>> enrollList = merchantSalerDao.getPageEnrollList((String) da.get("id"), (Integer) da.get("showNum"), 0);
                        if (null != enrollList && enrollList.size() > 0) {
                            for (Map<String, Object> enroll : enrollList) {
                                int status = this.getEnrollStatus((String) enroll.get("enrollId"));
                                enroll.put("status", status);
                            }
                        }
                        Integer enrollCount = merchantSalerDao.getEnrollCount((String) da.get("id"));
                        da.put("enrollCount", enrollCount);
                        da.put("items", enrollList);
                        break;
                    default:
                        break;
                }
            }
            stringRedisTemplate.opsForValue().set("home:pagelist_" + orgId + "_" + customerId, JSON.toJSONString(pageList, SerializerFeature.WriteMapNullValue), 15, TimeUnit.SECONDS);
        } else {
            pageList = (List<Map<String, Object>>) JSON.parse(pageListStr);
        }
        return pageList;
    }

    private void getGoodsItems(String orgId, String customerId, Map<String, Object> da, Integer moduleType, Integer isAll, Integer isAllIntegral) {
        String tipsShow = da.get("tipsShow").toString();
        if ("0".equals(tipsShow)) {
            da.put("goodsTitle", "");
            da.put("goodsDesc", "");
        }
        int type;
        if (orgId.equals(customerId)) {
            // 大b
            type = 0;
        } else {
            // 小b
            type = 1;
        }
        Integer showType = Integer.valueOf(da.get("showType").toString());
        if (2 == showType) {//分组商品
            List<Map<String, Object>> goodsList = new ArrayList<>();
            Integer goodsCount = 0;
            if (da.containsKey("goodsGroupId") && !StringUtils.isEmpty(da.get("goodsGroupId"))) {
                goodsList = merchantSalerDao.getGoodsByGroupId((Integer) da.get("goodsGroupId"), (Integer) da.get("showNum"), orgId, type, customerId, moduleType, isAll);
                for (Map<String, Object> go : goodsList) {
                    if ("1".equals(go.get("saler").toString())) {
                        go.put("isShare", "1");
                    } else {
                        go.put("isShare", "0");
                    }
                    go.put("goodsPrice", go.get("moneyAmount"));
                    if (!StringUtils.isEmpty(go.get("isSeckill")) && "1".equals(go.get("isSeckill").toString())) {
                        this.getKillThings(go);
                    }
                }
                goodsCount = merchantSalerDao.getGoodsCountByGroupId((Integer) da.get("goodsGroupId"), type, customerId, orgId, moduleType);
            }
            da.put("items", goodsList);
            da.put("goodsCount", goodsCount);
        }
        if (1 == showType) {//自定义商品
            Map<String, Object> paramCustom = new HashMap<>();
            paramCustom.put("moduleId", da.get("id"));
            paramCustom.put("moduleType", da.get("moduleType"));
            Object showNum = da.get("showNum");
            Integer limit;
            if (null == showNum) {
                limit = 0;
            } else {
                limit = Integer.valueOf(da.get("showNum").toString());
            }
            paramCustom.put("showNum", limit);
            paramCustom.put("type", type);
            paramCustom.put("customerId", customerId);
            paramCustom.put("orgId", orgId);
            paramCustom.put("isAll", isAll);
            paramCustom.put("isAllIntegral", isAllIntegral);
            List<Map<String, Object>> goodsList = new ArrayList<>();
            Integer goodsCount = 0;
            if (Integer.parseInt(da.get("moduleType").toString()) == 10) {
                goodsList = merchantSalerDao.getListIntGoodsCustom(paramCustom);
                goodsCount = merchantSalerDao.getListIntGoodsCustomCount(paramCustom);
            } else {
                goodsCount = merchantSalerDao.getListGoodsCustomCount(paramCustom);
                goodsList = merchantSalerDao.getListGoodsCustom(paramCustom);
            }

            da.put("goodsCount", goodsCount);
            for (Map<String, Object> go : goodsList) {
                if ("1".equals(go.get("saler").toString())) {
                    go.put("isShare", "1");
                } else {
                    go.put("isShare", "0");
                }
                go.put("goodsPrice", go.get("moneyAmount"));
                if (!StringUtils.isEmpty(go.get("isSeckill")) && "1".equals(go.get("isSeckill").toString())) {
                    this.getKillThings(go);
                }
            }
            da.put("items", goodsList);
        }
    }

    @Override
    public void getKillThings(Map mallGoods) {
        try {
            Map<String, Object> seckillMap;
            String seckillMapStr = stringRedisTemplate.opsForValue().get("goodsSeckill:" + mallGoods.get("goodsId").toString());
            if (StringUtils.isEmpty(seckillMapStr)) {
                seckillMap = mallDao.getSeckillByGoodsId(mallGoods.get("goodsId").toString());
                stringRedisTemplate.opsForValue().set("goodsSeckill:" + mallGoods.get("goodsId").toString(), JSON.toJSONString(seckillMap), 15, TimeUnit.SECONDS);
            } else {
                seckillMap = (Map<String, Object>) JSON.parse(seckillMapStr);
                SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                seckillMap.put("startTime", df2.format(new Date(Long.parseLong(seckillMap.get("startTime").toString()))));
                seckillMap.put("endTime", df2.format(new Date(Long.parseLong(seckillMap.get("endTime").toString()))));
            }
            if (seckillMap != null && seckillMap.size() > 0) {
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1 = df.parse(startTime);
                Date sd2 = df.parse(endTime);
                Date nowDate = new Date();
                mallGoods.put("seckillAllSecond", (sd2.getTime() - sd1.getTime()) / 1000);
                if (sd1.after(nowDate)) {
                    //未开始
                    mallGoods.put("seckillStatus", 0);
                    mallGoods.put("seckillSecond", (sd1.getTime() - nowDate.getTime()) / 1000);
                } else if (nowDate.after(sd2)) {
                    //已结束
                    mallGoods.put("seckillStatus", 2);
                    mallGoods.put("seckillSecond", (nowDate.getTime() - sd2.getTime()) / 1000);
                } else {
                    //进行中
                    mallGoods.put("seckillStatus", 1);
                    mallGoods.put("seckillSecond", (sd2.getTime() - nowDate.getTime()) / 1000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, Object>> getPageAllEnrollList(Map<String, Object> param) {
        List<Map<String, Object>> pageAllEnrollList = merchantSalerDao.getPageAllEnrollList(param);
        if (null != pageAllEnrollList && pageAllEnrollList.size() > 0) {
            for (Map<String, Object> enroll : pageAllEnrollList) {
                enroll.put("status", this.getEnrollStatus(enroll.get("enrollId").toString()));
            }
        }
        return pageAllEnrollList;
    }

    /**
     * 报名状态
     *
     * @param enrollId
     * @return 0 报名关闭 1 待报名 2 报名结束 3 报名已满 4 报名中
     */
    @Override
    public int getEnrollStatus(String enrollId) {
        Map<String, Object> param = new HashMap<>();
        param.put("enrollId", enrollId);

        Map<String, Object> info = enrollActiveDao.getInfo(param);
        if (info == null) {
            return 0;
        }
        String startTime = null;
        if (!StringUtils.isEmpty(info.get("startTime"))) {
            startTime = info.get("startTime").toString();
        }
        String endTime = null;
        if (!StringUtils.isEmpty(info.get("endTime"))) {
            endTime = info.get("endTime").toString();
        }
        String status = (String) info.get("status");

        String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 获取已报名人数
        Integer realNum = enrollActiveDao.getRealNum(enrollId);
        // 获取设置的报名总人数 减去 初始化的总人数
        Integer setNum = enrollActiveDao.getSetNum(enrollId);
        // 获取是否存在不限人数的报名项
        Integer unlimited = enrollActiveDao.unlimited(enrollId);
        if ("0".equals(status)) {
            // 报名关闭
            return 0;
        } else if (!StringUtils.isEmpty(startTime) && nowTime.compareTo(startTime) < 0) {
            // 待报名
            return 1;
        } else if (!StringUtils.isEmpty(endTime) && nowTime.compareTo(endTime) > 0) {
            // 报名结束
            return 2;
        } else if (unlimited < 1 && realNum >= setNum) {
            // 报名已满
            return 3;
        } else {
            //报名中
            return 4;
        }
    }

    /**
     * 加盟代理和推广员开通审核
     */
    @Override
    public String customerCheck(String type, String customerId, String orgId, String pid) {
        if (StringUtils.isEmpty(pid)) {
            pid = "";
        }
        Map<String, Object> param = new HashMap<>(3);
        param.put("type", type);
        param.put("customerId", customerId);
        param.put("orgId", orgId);
        Map<String, Object> check = merchantSalerDao.getSwitch(param);
        Integer apSwitch = 0;
        if (null != check) {
            if ("promoter".equals(type)) {
                apSwitch = (Integer) check.get("promoterCheck");
            }
            if ("agent".equals(type)) {
                apSwitch = (Integer) check.get("agentCheck");
            }
        }
        if (1 == apSwitch) {
            Map<String, Object> customerCheck = merchantSalerDao.getCustomerCheck(param);
            if (null == customerCheck) {
                throw GlobalException.build("审核未通过，操作失败");
            }
            String checkPid = (String) customerCheck.get("pid");
            if (!StringUtils.isEmpty(checkPid)) {
                pid = checkPid;
            }
        }
        return pid;
    }

    @Override
    public Map<String, Object> getCustomerCheckInfo(Map<String, String> param) {
        Map<String, Object> customerCheckInfo = merchantSalerDao.getCustomerCheckInfo(param);
        if (null == customerCheckInfo) {
            Map<String, Object> data = new HashMap<>(1);
            data.put("status", -1);
            return data;
        }
        return customerCheckInfo;
    }

    @Override
    public List<Map<String, Object>> getSalerPromoterSonBillList(String pcustomerId, String customerId) {
        List<Map<String, Object>> salerPromoterSonBillList = merchantSalerDao.getSalerPromoterSonBillList(pcustomerId, customerId);
        for (Map<String, Object> da : salerPromoterSonBillList) {
            String amount = da.get("amount").toString();
            da.put("amount", NumberUtils.fenToYuan(Long.valueOf(amount)));
        }
        return salerPromoterSonBillList;
    }

    @Override
    public Long getUserTotalVolume(String pCustomerId, int type, String orgId, String startTime, String endTime) {
        Long userTotalVolume = merchantSalerDao.getUserTotalVolume(pCustomerId, type, orgId, startTime, endTime);
        Long userTotalVolumeScore = merchantSalerDao.getUserTotalVolumeScore(pCustomerId, type, orgId, startTime, endTime);
        return userTotalVolume + userTotalVolumeScore;
    }

    @Override
    public Integer getOrderCount(String customerId, String orgId) {
        Integer orderCount = merchantSalerDao.getOrderCount(customerId, orgId);
        Integer enrollOrderCount = merchantSalerDao.getEnrollOrderCount(customerId, orgId);
        return enrollOrderCount + orderCount;
    }

    @Override
    public Long getSettleFee(String customerId) {
        return merchantSalerDao.getSettleFee(customerId);
    }

    @Override
    public List<Map<String, Object>> getAllPromoterList() {
        return merchantSalerDao.getAllPromoterList();
    }

    @Override
    public Integer getTodaySonCount(Map<String, Object> param) {
        return merchantSalerDao.getTodaySonCount(param);
    }

    @Override
    public Integer getTodayAllRebate(Map<String, Object> param) {
        return merchantSalerDao.getTodayAllRebate(param);
    }

    @Override
    public Integer getTodayServiceFee(Map<String, Object> param) {
        return merchantSalerDao.getTodayServiceFee(param);
    }

    @Override
    public Integer getTodayRecommendFee(Map<String, Object> param) {
        return merchantSalerDao.getTodayRecommendFee(param);
    }

    @Override
    public void saveAchievementSettlement(Map<String, Object> param) {
        merchantSalerDao.saveAchievementSettlement(param);
    }

    @Override
    public Long getSonSettleFee(Map<String, Object> data) {
        return merchantSalerDao.getSonSettleFee(data);
    }

    @Override
    public Long getSonTotalVolume(Map<String, Object> data) {
        return merchantSalerDao.getSonTotalVolume(data) + merchantSalerDao.getSonTotalVolumeScore(data);
    }

    @Override
    public Map<String, Object> getPromoterDetail(Map<String, Object> param) {

        Map<String, Object> resData = new HashMap<>();

        //加盟代理基本信息
        Map<String, Object> customerInfo = merchantSalerDao.getCustomerInfo(param);
        if (null == customerInfo) {
            throw GlobalException.build("未找到该用户的数据");
        }
        String pCustomerName = "";
        if (!StringUtils.isEmpty(customerInfo.get("pid"))) {
            Map<String, Object> pInfo = mallBoomService.getCustomerInfoByCustomerId(customerInfo.get("pid").toString());
            if (!StringUtils.isEmpty(pInfo.get("customerName"))) {
                pCustomerName = pInfo.get("customerName").toString();
            }
        }
        customerInfo.put("pCustomerName", pCustomerName);
        if (StringUtils.isEmpty(customerInfo.get("customerName")) && !StringUtils.isEmpty(customerInfo.get("bindPhone"))) {
            customerInfo.put("customerName", "手机尾号" + customerInfo.get("bindPhone").toString().substring(7) + "用户");
        }
        resData.put("baseInfo", customerInfo);

        //加盟代理业绩概览
        Long userTotalVolumeTemp = merchantSalerDao.getUserTotalVolume(param.get("customerId").toString(), 1, param.get("orgId").toString(), null, null);//累计下级交易额
        Long userTotalVolumeTempScore = merchantSalerDao.getUserTotalVolumeScore(param.get("customerId").toString(), 1, param.get("orgId").toString(), null, null);//累计下级交易额
        Long promoterTotalVolumeTemp = merchantSalerDao.getUserTotalVolume(param.get("customerId").toString(), 2, param.get("orgId").toString(), null, null);//累计下级代理交易额
        Long promoterTotalVolumeTempScore = merchantSalerDao.getUserTotalVolumeScore(param.get("customerId").toString(), 2, param.get("orgId").toString(), null, null);//累计下级代理交易额
        Integer orderCount = merchantSalerDao.getOrderCount(param.get("customerId").toString(), param.get("orgId").toString());//累计推广订单数
        Integer EnrollCount = merchantSalerDao.getEnrollOrderCount(param.get("customerId").toString(), param.get("orgId").toString());//累计推广订单数
        Long totalBackFeeTemp = merchantSalerDao.getTotalBackFee(param);//累计返润金额
        Long userTotalCashTemp = merchantSalerDao.getUserTotalCash(param);//累计提现
        Integer sonCustomerCount = merchantSalerDao.getSonCustomerCountBack(param.get("customerId").toString(), param.get("orgId").toString(), 1);//累计下级
        Long settleFeeTemp = merchantSalerDao.getSettleFee(param.get("customerId").toString());//结算中

        Map<String, Object> achieveInfo = new HashMap<>();
        achieveInfo.put("userTotalVolume", NumberUtils.fenToYuan(userTotalVolumeTemp + userTotalVolumeTempScore));
        achieveInfo.put("promoterTotalVolume", NumberUtils.fenToYuan(promoterTotalVolumeTemp + promoterTotalVolumeTempScore));
        achieveInfo.put("orderCount", orderCount + EnrollCount);
        achieveInfo.put("totalBackFee", NumberUtils.fenToYuan(totalBackFeeTemp));
        achieveInfo.put("userTotalCash", NumberUtils.fenToYuan(userTotalCashTemp));
        achieveInfo.put("settleFee", NumberUtils.fenToYuan(settleFeeTemp));
        achieveInfo.put("sonCustomerCount", sonCustomerCount);
        resData.put("achieveInfo", achieveInfo);

        return resData;
    }

    @Override
    public List<Map<String, Object>> getAchieveList(Map<String, Object> param) {
        List<Map<String, Object>> achieveList = merchantSalerDao.getAchieveList(param);
        for (Map<String, Object> al : achieveList) {
            al.put("allRebate", NumberUtils.fenToYuan(Long.valueOf(al.get("allRebate").toString())));
            al.put("serviceFee", NumberUtils.fenToYuan(Long.valueOf(al.get("serviceFee").toString())));
            al.put("recommendFee", NumberUtils.fenToYuan(Long.valueOf(al.get("recommendFee").toString())));
            al.put("sonDealFee", NumberUtils.fenToYuan(Long.valueOf(al.get("sonDealFee").toString())));
            al.put("promoterDealFee", NumberUtils.fenToYuan(Long.valueOf(al.get("promoterDealFee").toString())));
            al.put("authorFee", NumberUtils.fenToYuan(Long.valueOf(al.get("authorFee").toString())));
        }
        return achieveList;
    }

    @Override
    public Integer getSonOrderCount(Map<String, Object> param) {
        Integer sonOrderCount = merchantSalerDao.getSonOrderCount(param);
        Integer sonEnrollOrderCount = merchantSalerDao.getSonEnrollOrderCount(param);
        return sonOrderCount + sonEnrollOrderCount;
    }

    @Override
    public void addbalance(String ymd) {
        List<Map> maps = merchantSalerDao.selectOpenData(ymd);
        for (Map map : maps) {
            merchantSalerDao.addbalance(map);
        }
    }

    @Override
    public Long getCustomerFreeze(Map<String, Object> params) {
        Long customerFreeze = 0l;
        String customerId = params.get("customerId").toString();

        List<Map<String, Object>> result = this.getOrderListFreeze(params);

        for (Map<String, Object> x : result) {
            if (x.get("isEnd") != null && "0".equals(x.get("isEnd").toString())) {
                Long amount = 0l;
                if (x.get("amount") != null) {
                    amount = Long.valueOf(x.get("amount").toString());
                }
                customerFreeze = customerFreeze + amount;
            }
            String amount = x.get("amount") == null ? "0" : x.get("amount").toString();
            x.put("amount", NumberUtils.fenToYuan(Long.parseLong(amount)));
            x.put("customerId", customerId);
            List<Map<String, Object>> temp = merchantSalerDao.tradeListFreeze(x);
            for (Map<String, Object> m : temp) {
                if (m.get("isEnd") != null && "0".equals(m.get("isEnd").toString())) {
                    if (m.get("refundStatus") != null && "2".equals(m.get("refundStatus").toString())) {
                        Long refundAmount = 0l;
                        if (m.get("amount") != null) {
                            refundAmount = Long.valueOf(m.get("amount").toString());
                        }
                        customerFreeze = customerFreeze - refundAmount;
                    }
                }
            }
        }
        return customerFreeze;
    }

    @Override
    public List<Map<String, Object>> getOrderListFreeze(Map<String, Object> params) {
        List<Map<String, Object>> orderList = merchantSalerDao.orderListFreeze(params);
        if (orderList.size() > 0) {
            orderList.forEach(o -> {
                if (o.get("orderType") != null && ("39".equals(o.get("orderType").toString()) || "41".equals(o.get("orderType").toString()))) {
                    o.put("type", "sale");
                } else {
                    String orderSn = o.get("orderSn").toString();
                    Map<String, Object> moInfo = null;
                    if (orderSn.startsWith("I")) {
                        moInfo = merchantSalerDao.getIntegralOrderInfoByOrderSn(orderSn);
                    } else if (orderSn.startsWith("E")) {
                        moInfo = merchantSalerDao.getMerchantOrderInfoByOrderSn(orderSn);
                        if (moInfo == null) {
                            Map<String, Object> soInfo = merchantSalerDao.getSalerOrderInfoByOrderSn(o.get("orderSn").toString());
                            if (soInfo != null) {
                                o.put("amount", soInfo.get("amount"));
                                o.put("type", "sale");
                            }
                        }
                    }
                    if (moInfo != null) {
                        o.put("amount", moInfo.get("orderTotalPrice"));
                        o.put("type", "order");
                    } else {
                        if (orderSn.startsWith("Y")) {
                            Map<String, Object> erInfo = merchantSalerDao.getEnrollRecordInfoByOrderSn(o.get("orderSn").toString());
                            if (erInfo != null) {
                                o.put("amount", erInfo.get("payAmount"));
                                o.put("type", "enroll");
                            } else {
                                Map<String, Object> formInfo = merchantSalerDao.getFormInfoByOrderSn(o.get("orderSn").toString());
                                if (formInfo != null) {
                                    o.put("amount", formInfo.get("amount"));
                                    o.put("type", "enroll");
                                } else {
                                    o.put("amount", 0);
                                    o.put("type", "");
                                }
                            }
                        } else if (orderSn.startsWith("V")) {
                            Map<String, Object> vipInfo = merchantSalerDao.getvipLogInfoByOrderSn(o.get("orderSn").toString());
                            if (vipInfo != null) {
                                o.put("amount", vipInfo.get("amount"));
                                o.put("type", "vip");
                            } else {
                                o.put("amount", 0);
                                o.put("type", "");
                            }
                        } else {
                            o.put("amount", 0);
                            o.put("type", "");
                        }
                    }
                }
            });
        }
        return orderList;
    }

    @Override
    public List<Map<String, Object>> getCustomPosterList(Map<String, Object> params) {
        return merchantSalerDao.getCustomPosterList(params);
    }

    @Override
    public Long getCrossUserTotalVolume(String customerId, String startTime, String endTime) {
        List<Map<String, Object>> sonCustomerList = merchantSalerDao.getSonCustomerList(customerId);
        long total = 0L;
        for (Map<String, Object> sonCustomer : sonCustomerList) {
            String sonCustomerId = sonCustomer.get("customerId").toString();
            String parentSaveTime = sonCustomer.get("parentSaveTime").toString();
            parentSaveTime = parentSaveTime.substring(0, parentSaveTime.length() - 2);
            Long volume = getSonCrossUserTotalVolume(sonCustomerId, parentSaveTime, startTime, endTime);
            total = total + volume;
        }
        return total;
    }

    private Long getSonCrossUserTotalVolume(String pCustomerId, String parentSaveTime, String startTime, String endTime) {
        Long userTotalVolume = merchantSalerDao.getCrossUserTotalVolume(pCustomerId, parentSaveTime, startTime, endTime);
        Long userTotalVolumeScore = merchantSalerDao.getCrossUserTotalVolumeScore(pCustomerId, parentSaveTime, startTime, endTime);
        return userTotalVolume + userTotalVolumeScore;
    }

    @Override
    public Long getAuthorFee(String customerId, String orgId, String strStart, String strEnd) {
        return merchantSalerDao.getAuthorFee(customerId, orgId, strStart, strEnd);
    }

    @Override
    public Map<String, Object> getFooterList(String customerId) {
        Map<String, Object> result = merchantSalerDao.getFooter(customerId);
        if (null != result) {
            // 获取当前机构的默认首页pageID
            Integer id = merchantSalerDao.getHomePageIdByCustomerId(customerId);
            result.put("pageId", id);
            List<Map<String, Object>> itemList = merchantSalerDao.getFooterItem(Integer.parseInt(result.get("id").toString()));
            result.put("itemList", itemList);
        }
        return result;
    }

    @Override
    public Map<String, Object> getPageInfo(Integer pageId, Integer isAll, Boolean noCache, HttpServletRequest request, boolean isH5, Integer isAllIntegral) {
        Map<String, Object> result;
        String key = "pageInfo:" + pageId + ":" + isAll;
        String pageListStr = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(pageListStr) || noCache) {
            result = merchantSalerDao.getPageInfo(pageId);
            if (StringUtils.isEmpty(result)) {
                throw GlobalException.build(404, "页面不存在");
            }
            List<Map<String, Object>> moduleList = merchantSalerDao.getModuleListById(pageId);
            String orgId = result.get("orgId").toString();
            String customerId = result.get("customerId").toString();
            List<Map<String, Object>> moduleListEnd = new ArrayList<>();
            for (Map<String, Object> module : moduleList) {
                module.put("goodsCount", 0);
                module.put("enrollCount", 0);
                int moduleType = Integer.parseInt(module.get("moduleType").toString());
                // 针对不同模块获取对应的数据
                switch (moduleType) {
                    case 1:
                        // 图片广告
                    case 2:
                        // 图文导航
                        List<Map<String, Object>> items = merchantSalerDao.getModuleImageListById(module.get("id").toString());
                        module.put("items", items);
                        moduleListEnd.add(module);
                        break;
                    case 10:
                        // 积分商品
                    case 3:
                        // 商品
                    case 4:
                        // 知识商品
                        LOGGER.info("moduleType:" + moduleType + "orgId:" + orgId + "customerId:" + customerId);
                        if (moduleType == 10 && !orgId.equals(customerId) && isAllIntegral == null){
                            isAllIntegral = 1;
                        }
                        this.getGoodsItems(orgId, customerId, module, moduleType, isAll, isAllIntegral);
                        moduleListEnd.add(module);
                        break;
                    case 5:
                        List<Map<String, Object>> enrollList = merchantSalerDao.getPageEnrollList((String) module.get("id"), (Integer) module.get("showNum"), isAll);
                        if (null != enrollList && enrollList.size() > 0) {
                            for (Map<String, Object> enroll : enrollList) {
                                int status = this.getEnrollStatus((String) enroll.get("enrollId"));
                                enroll.put("status", status);
                            }
                        }
                        Integer enrollCount = merchantSalerDao.getEnrollCount((String) module.get("id"));
                        module.put("enrollCount", enrollCount);
                        module.put("items", enrollList);
                        moduleListEnd.add(module);
                        break;
                    case 6:
                        //优惠券
                        List<Map<String, Object>> listc = merchantSalerDao.getPageCouponList((String) module.get("id"));
                        if (listc != null && listc.size() > 0) {
                            List<Map<String, Object>> couponListMap = new ArrayList<>();
                            List<String> couponIdList = new ArrayList<>();
                            for (Map c : listc) {
                                couponIdList.add(c.get("couponId").toString());
                            }
                            couponListMap = this.getCouponListByCouponIds(couponIdList, request, isH5, customerId);
                            List<Map<String, Object>> couponListMaps = new ArrayList<>();
                            for (String couponId : couponIdList) {
                                for (Map couponMap : couponListMap) {
                                    if (couponId.equals(couponMap.get("couponId").toString())) {
                                        couponListMaps.add(couponMap);
                                    }
                                }
                            }
                            module.put("items", couponListMaps);
                            if (couponListMaps.size() > 0) {
                                moduleListEnd.add(module);
                            }
                        }
                        break;
                    case 7:
                        //表单
                        List<String> newEnrollList = merchantSalerDao.getPageNewEnrollList((String) module.get("id"));
                        List<Map<String, Object>> newEnrollListMap = new ArrayList<>();
                        if (newEnrollList != null && newEnrollList.size() > 0) {
                            FormLoginDto formLoginDto = formFilter.getFormLoginDto(request, isH5);
                            Map params = new HashMap();
                            String newStr = newEnrollList.stream().collect(Collectors.joining(","));
                            params.put("ids", newStr);
                            if (isH5) {
                                params.put("isH5", 1);
                            }
                            List<Map<String, Object>> list = (List<Map<String, Object>>) formRequest.doRequest("/pc/form/templates/getAllList", params, formLoginDto);
                            if (list != null && list.size() > 0) {
                                Integer showNum = (Integer) module.get("showNum");
                                Integer count = 0;
                                for (Map newEnroll : list) {
                                    if (count < showNum || (!isH5 && isAll == 1)) {
                                        //enrollId,title,shareContent,cover
                                        Map enrollMap = new HashMap();
                                        enrollMap.put("formId", newEnroll.get("formId"));
                                        enrollMap.put("formTitle", newEnroll.get("formTitle"));
                                        enrollMap.put("shareContent", newEnroll.get("shareContent"));
                                        enrollMap.put("cover", newEnroll.get("cover"));
                                        enrollMap.put("status", newEnroll.get("status"));
                                        String statusName = "待报名";
                                        if (!StringUtils.isEmpty(newEnroll.get("statusName"))) {
                                            statusName = newEnroll.get("statusName").toString();
                                            if ("报名中".equals(statusName)) {
                                                //如果是报名中 判断是否  报名已满
                                                if (!StringUtils.isEmpty(newEnroll.get("formId"))) {
                                                    Map map = new HashMap();
                                                    map.put("id", Long.valueOf(newEnroll.get("formId").toString()));
                                                    Map resmap = (Map) formRequest.doRequest("/pc/form/templates/getFormStatus", map, formLoginDto);
                                                    if (resmap != null && !StringUtils.isEmpty(resmap.get("statusName"))) {
                                                        statusName = resmap.get("statusName").toString();
                                                    }
                                                }
                                            }

                                        }
                                        enrollMap.put("statusName", statusName);
                                        newEnrollListMap.add(enrollMap);
                                    } else {
                                        break;
                                    }
                                    count++;
                                }
                            }
                        }
                        module.put("formCount", newEnrollList.size());
                        module.put("items", newEnrollListMap);
                        moduleListEnd.add(module);
                        break;
                    case 8:
                        //视频
                        List<Map<String, Object>> videos = merchantSalerDao.getVideoModuleImageListById(module.get("id").toString());
                        module.put("items", videos);
                        moduleListEnd.add(module);
                        break;
                    case 9:
                        //权益卡
                        List<Map<String, Object>> vipList = merchantSalerDao.getPageVipList((String) module.get("id"));
                        module.put("items", vipList);
                        if (vipList != null && vipList.size() > 0) {
                            moduleListEnd.add(module);
                        }
                        break;
                    default:
                        break;
                }
            }
            result.put("moduleList", moduleListEnd);
            if (!StringUtils.isEmpty(result.get("pageKind"))) {
                Integer pageKind = Integer.valueOf(result.get("pageKind").toString());
                if (pageKind == -2) {
                    //个人中心
                    List<Map<String, Object>> markings = merchantSalerDao.getMarkingsByOrgId(orgId, isH5);
                    if (markings == null || markings.size() == 0) {
                        //新增营销活动
                        markings = this.defaultMarking(orgId);
                    }
                    result.put("markings", markings);
                    String keys = "marking:" + orgId;
                    stringRedisTemplate.delete(keys);
                }
            }
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(result, SerializerFeature.WriteMapNullValue), 15, TimeUnit.SECONDS);
        } else {
            result = (Map<String, Object>) JSON.parse(pageListStr);
        }
        return result;
    }

    //新增默认营销活动
    @Override
    public List<Map<String, Object>> defaultMarking(String orgId) {
        merchantSalerDao.insertDefaultMarking(orgId);
        return merchantSalerDao.getMarkingsByOrgId(orgId, false);
    }

    //获取优惠券
    @Override
    public List<Map<String, Object>> getCouponListByCouponIds(List<String> couponIds, HttpServletRequest request, Boolean isH5, String customerId) {
        CouponCustomerInfo customerInfo = null;
        if (isH5) {
            customerInfo = requestFilter.getCouponCustomerInfo(request);
            customerInfo.setCustomerId(customerId);
        } else {
            PcUserInfo userInfo = userInfoUtil.getPcUserInfo(request);
            customerInfo = CouponCustomerInfo
                    .builder()
                    .customerId(userInfo.getSaler() ? userInfo.getCustomerId() : userInfo.getOrgId())
                    .customerName(userInfo.getAdminName())
                    .customerPhone("15012345678")
                    .cover("")
                    .orgId(userInfo.getOrgId())
                    .build();
        }
        //查询符合该商品的优惠券
        Map<String, Object> param = new HashMap<>();
        List<Map<String, Object>> dataList = null;
        if (couponIds != null && couponIds.size() > 0) {
            param.put("couponIds", String.join(",", couponIds));
            param.put("notEnd", 1);
            Object list = couponRequest.doRequest("coupon-all-list", param, customerInfo);
            dataList = (List<Map<String, Object>>) list;
            if (null != dataList && dataList.size() > 0) {
                for (Map<String, Object> da : dataList) {
                    Map<String, Object> couponGoodsData = merchantSalerDao.getCouponGoodsData(da.get("couponId").toString());
                    if (null != couponGoodsData) {
                        da.put("customerType", couponGoodsData.get("customerType"));
                        da.put("goodsType", couponGoodsData.get("goodsType"));
                        da.put("customerCouponNum", couponGoodsData.get("customerCouponNum"));
                    }
                }
            }
        }
        if (dataList == null) {
            dataList = new ArrayList<>();

        }
        return dataList;
    }

    @Override
    public Integer getHomePageIdByCustomerId(String customerId) {
        return merchantSalerDao.getHomePageIdByCustomerId(customerId);
    }

    @Override
    public Object getPageAllFormlist(Map<String, Object> param, HttpServletRequest request) {
        List<String> newEnrollList = merchantSalerDao.getPageNewEnrollList((String) param.get("id"));
        if (newEnrollList != null && newEnrollList.size() > 0) {
            FormLoginDto formLoginDto = formFilter.getFormLoginDto(request, true);
            String newStr = newEnrollList.stream().collect(Collectors.joining(","));
            param.put("ids", newStr);
            param.put("isPage", 1);
            param.put("isH5", 1);
            return formRequest.doRequest("/pc/form/templates/getAllList", param, formLoginDto);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Object> windowInfo(String orgId) {
        Map param = merchantSalerDao.getInfo(orgId);
        if (param != null && !StringUtils.isEmpty(param.get("id"))) {
            String windowId = param.get("id").toString();
            List<Map> subs = merchantSalerDao.getSubs(windowId);
            param.put("subs", subs);
            //查询首页id
            Long homePageId = merchantSalerDao.getHomePageId(orgId);
            param.put("homePageId", homePageId);
        } else {
            param = new HashMap();
            param.put("isOpen", 0);
        }
        return param;
    }

    @Override
    public List<Map<String, Object>> getMarkings(String orgId) {
        List<Map<String, Object>> markings;
        String key = "marking:" + orgId;
        String markingsString = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(markingsString)) {
            markings = merchantSalerDao.getMarkingsByOrgId(orgId, true);
            if (markings == null || markings.size() == 0) {
                //新增营销活动
                markings = this.defaultMarking(orgId);
            } else {
                for (int i = markings.size() - 1; i >= 0; i--) {
                    if (!StringUtils.isEmpty(markings.get(i).get("type")) && "10".equals(markings.get(i).get("type").toString())
                            && !StringUtils.isEmpty(markings.get(i).get("isChecked")) && "1".equals(markings.get(i).get("isChecked").toString())
                    ) {
                        Integer status = merchantSalerDao.getSignStatus(orgId);
                        if (status == null || status == 0) {
                            markings.remove(i);
                        }
                    }
                }
            }
        } else {
            markings = (List<Map<String, Object>>) JSON.parse(markingsString);
        }
        return markings;
    }

    @Override
    public Map getUserCenter(String orgId) {
        return merchantSalerDao.getUserCenter(orgId);
    }
}
